<?php
namespace Hilaoyu\LaravelExtend\Services\ThirdPartyLogin\Drivers;

use Hilaoyu\Utils\UtilHttp;

/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2017/12/21
 * Time: 14:56
 */
class DriverWechat extends AbstractDriver
{

    const API_CODE_MP = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
    const API_CODE_OPEN = 'https://open.weixin.qq.com/connect/qrconnect?';
    const API_ACCESS_TOKEN = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    const API_USER_INFO = 'https://api.weixin.qq.com/sns/userinfo';

    protected $AppId = '';
    protected $AppSecret = '';
    protected $RedirectUri = '';
    protected $AppType = 'open';
    protected $DriverName = '';

    public $access_token = '';
    public $openid = '';
    public $unionid = '';

    /*
     * @$config = [
     * 'app_id'=>'',
     * 'app_secret'=>'',
     * 'redirect_uri'=>'',
     * 'type'=>'',mp | open 对应公众平台和开方平台
     * ]
     * */



    public function __construct(array $config)
    {
        $this->AppId = isset($config['app_id']) ? $config['app_id'] : '';
        $this->AppSecret = isset($config['app_secret']) ? $config['app_secret'] : '';
        //$this->RedirectUri = isset($config['redirect_uri']) ? $config['redirect_uri'] : '';
        $this->AppType = isset($config['type']) ? $config['type'] : '';
        $this->DriverName = isset($config['driver']) ? $config['driver'] : 'wechat';
    }

    public function getDriverName()
    {
        return $this->DriverName;
    }

    public function buildLoginUrl($state=''){

        $url = '';
        $params = [
            'appid' => $this->AppId,
            'redirect_uri' => route('web.l-e-s.third_party_login.return'),
            'response_type' => 'code',
            'state' => trim($state),
        ];

        switch ($this->AppType){
            case 'open':
                $url = self::API_CODE_OPEN;
                $params['scope'] = 'snsapi_login';
                break;
            case 'mp':
                $url = self::API_CODE_MP;
                $params['scope'] = 'snsapi_userinfo';
                break;

            default:
                $this->setError('config type error,only "open" or "mp" allowed');
                break;
        }

        return empty($url) ? false : $url . UtilHttp::paramsArrayToStr($params) . '#wechat_redirect';
    }


    public function getAuthorization($code){
        $params = [
            'appid'=>$this->AppId,
            'secret'=>$this->AppSecret,
            'code'=>$code,
            'grant_type'=>'authorization_code',
        ];


        $remote_re = UtilHttp::RequestJson(self::API_ACCESS_TOKEN,$params,'get');
        if(!$remote_re){
            return false;
        }

        if(isset($remote_re['errcode']) || isset($remote_re['errmsg'])){
            if(isset($remote_re['errcode'])){
                $this->setError('authorization return error: errcode '. $remote_re['errcode']);
            }
            if(isset($remote_re['errmsg'])){
                $this->setError('authorization return error: errmsg '. $remote_re['errmsg']);
            }

            return false;
        }

        if(empty($remote_re['access_token']) || empty($remote_re['openid']) ){
            $this->setError('authorization return access_token was empty');
            return false;
        }

        $this->access_token = $remote_re['access_token'];
        $this->openid = $remote_re['openid'];

        if(empty($remote_re['unionid'])){
            $remote_re['unionid'] = $remote_re['openid'];
        }
        $this->unionid = $remote_re['unionid'];

        return $remote_re;

    }

    public function getOpenId(array $authorization = [])
    {
        // TODO: Implement getOpenId() method.
        return isset($authorization['openid']) ? $authorization['openid'] : $this->openid;
    }

    public function getUnionId()
    {
        // TODO: Implement getUnionId() method.
        return $this->unionid;
    }

    public function getUserinfo($openid='',$access_token=''){
        $openid = empty($openid) ? $this->openid : $openid;
        $access_token = empty($access_token) ? $this->access_token : $access_token;
        $params = [
            'access_token'=>$access_token,
            'openid'=>$openid,
            'lang'=>'zh-CN',
        ];
        $remote_re = UtilHttp::RequestJson('https://api.weixin.qq.com/sns/userinfo',$params,'get');
        if(!$remote_re){
            return false;
        }

        if(isset($remote_re['errcode']) || isset($remote_re['errmsg'])){
            if(isset($remote_re['errcode'])){
                $this->setError('user_info return error: errcode '. $remote_re['errcode']);
            }
            if(isset($remote_re['errmsg'])){
                $this->setError('user_info return error: errmsg '. $remote_re['errmsg']);
            }

            return false;
        }
        if(empty($remote_re['openid'])){
            $this->setError('user_info return openid was empty');
            return false;
        }
        if(empty($remote_re['unionid'])){
            $remote_re['unionid'] = $remote_re['openid'];
        }
        return $remote_re;
    }

}
